package com.firefly.admin.common.handle;

import lombok.extern.slf4j.Slf4j;
import com.firefly.admin.common.enums.ResultCodeEnum;
import com.firefly.admin.common.exception.BusinessException;
import com.firefly.admin.common.vo.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;

@RestControllerAdvice
@Component
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public Result<String> businessExceptionHandler(BusinessException e) {
        log.error(Arrays.toString(e.getStackTrace()));
        String message = e.getMessage();
        try {
            ResultCodeEnum resultCodeEnum = ResultCodeEnum.valueOf(message);
            return Result.getResult(resultCodeEnum);
        } catch (Exception e1) {
            return Result.error(ResultCodeEnum.ERROR.getCode(), message);
        }
    }


    @ResponseBody
    @ExceptionHandler(AccessDeniedException.class)
    public Result<String> accessDeniedExceptionHandler(AccessDeniedException e) {
        e.printStackTrace();
        log.error(Arrays.toString(e.getStackTrace()));
        return Result.getResult(ResultCodeEnum.FORBIDDEN);
    }

    @ResponseBody
    @ExceptionHandler(AuthorizationServiceException.class)
    public Result<String> authorizationServiceExceptionHandler(AuthorizationServiceException e) {
        e.printStackTrace();
        log.error(Arrays.toString(e.getStackTrace()));
        return Result.getResult(ResultCodeEnum.UNAUTHORIZED);
    }

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Result<String> runtimeExceptionHandler(RuntimeException e) {
        e.printStackTrace();
        log.error(Arrays.toString(e.getStackTrace()));
        return Result.getResult(ResultCodeEnum.ERROR);
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception e) {
        e.printStackTrace();
        log.error(Arrays.toString(e.getStackTrace()));
        return Result.getResult(ResultCodeEnum.ERROR);
    }
}
